package binaryTreeSearch;

public class BinaryTreeSearchReview {
    static class TreeNode {
        public int val;

        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    private TreeNode root;

    public boolean add(int val) {
        TreeNode node = new TreeNode(val);
        if(root == null) {
            root = node;
            return true;
        }
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null) {
            prev = cur;
            if(cur.val == val) {
                return false;
            } else if(cur.val > val) {
                cur = cur.left;
            } else {
                cur = cur.right;
            }
        }
        if(prev.val > val) {
            prev.left = node;
        } else {
            prev.right = node;
        }
        return true;
    }

    public boolean find(int key) {
        TreeNode cur = root;
        while(cur != null) {
            if (cur.val > key) {
                cur = cur.left;
            } else if(cur.val < key){
                cur = cur.right;
            } else {
                return true;
            }
        }
        return false;
    }

    public void remove(int key) {
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null) {
            if(cur.val == key) {
                break;
            } else if(cur.val > key) {
                prev = cur;
                cur = cur.left;
            } else {
                prev = cur;
                cur = cur.right;
            }
        }
        if(cur == null) {
            return;
        }
        // cur 上的值就是要删除的节点
        if(cur.left == null) {
            if(cur == root) {
                root = cur.right;
            } else if(prev.left == cur) {
                prev.left = cur.right;
            } else {
                prev.right = cur.right;
            }
        } else if(cur.right == null) {
            if(cur == root) {
                root = cur.left;
            } else if(prev.left == cur) {// 必须将这个放在 cur == root 后面，如果 cur == root 成立 那么 prev = null
                prev.left = cur.left;
            } else {
                prev.right = cur.left;
            }
        } else {
            TreeNode parent = cur;
            TreeNode child = parent.left;
            while(child.right != null) {
                parent = child;
                child = child.right;
            }
            parent.val = child.val;
            if(parent.left == child) {
                parent.left = child.left;
            } else {
                parent.right = child.left;
            }
        }
    }
}
